package com.amkai.aes.aesws;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.amkai.aes.generatedbeans.organization.Enterprise;
import com.amkai.common.extensions.hibernate.config.SiteManager;
import com.amkai.common.extensions.hibernate.config.manager.SessionManager;
import com.amkai.erx.communicator.InstallCert;

//http://10.0.0.135:8080/aesws/AmkaiForwarderServlet

public class AmkaiForwarderServlet extends HttpServlet {
	private static final Log log = LogFactory.getLog(AmkaiForwarderServlet.class);

	private static final String DELPHI_WS_URL = "DelphiWsService/DelphiWs";
	private static final long serialVersionUID = 1L;
	private SessionManager sm;
	private String urlStr;
       
    public AmkaiForwarderServlet() {
        super();
		try {
			sm = SiteManager.Start();
			sm.openSession();
			try {
				Enterprise ent = (Enterprise) sm.execute("from Enterprise ent").uniqueResult();
				if(ent != null) {
					urlStr = ent.getAmkaiRxURL();
					if(urlStr == null || urlStr.trim().length() == 0) {
						log.error("There is no AmkaiRx URL specified at Enterprise level");
					} else {
						if(!urlStr.endsWith("/")) urlStr += "/";
						urlStr += DELPHI_WS_URL;
						if(DUMP) System.out.println("Amkai Rx URL used to forward "+urlStr);
						log.info("Amkai Rx URL used to forward "+urlStr);
					}
				} else {
					log.error("There is no Enterprise exist in the Database");
				}
			} finally {
				sm.closeSession();
			}
		} catch (Exception e) {
			log.error("Error getting AmkaiRx URL",e);
		}

    }

    @Override
    public void init(ServletConfig config) throws ServletException {
    	super.init(config);
    }
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.getOutputStream().println("<html><body><h1>Amkai Forwarder Servlet</h1></body></html>");
		response.getOutputStream().flush();
	}
	//http://10.0.0.135:8080/aesws/AmkaiForwarderServlet
	private static final boolean DUMP = true;
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if(urlStr == null) {
			throw new ServletException("There is no valid AmkaiRx URL found.");
		} else {
			try {
				BufferedReader brRequest = new BufferedReader(new InputStreamReader(request.getInputStream()));
				String line = "";
				String requestBody = "";
				while((line = brRequest.readLine()) != null) {
					requestBody += line + "\n";
				}
				brRequest.close();
				
				if(DUMP) {
					System.out.println("Request :");
					System.out.println(requestBody);
				}
				log.info("FORWARD REQUEST "+requestBody);
				URL url = new URL(urlStr);
				HttpsURLConnection.setDefaultSSLSocketFactory(InstallCert.getFactory());
				HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
	
				conn.setReadTimeout(5*1000);
				conn.setConnectTimeout(5*1000);
				
				conn.setRequestMethod("POST");
				conn.setRequestProperty("Content-type: ", "text/xml");
				conn.setDoOutput(true);
				
				OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 
				wr.write(requestBody); 
				wr.flush();
//				wr.close();
				
				BufferedReader brResponse = new BufferedReader(new InputStreamReader(conn.getInputStream()));
				line = "";
				String responseBody = "";
				while((line = brResponse.readLine()) != null) {
					responseBody += line + "\n";
				}
				if(DUMP) {
					System.out.println("Response :");
					System.out.println(responseBody);
				}
				log.info("FORWARD RESPONSE "+responseBody);
				OutputStreamWriter wrRet = new OutputStreamWriter(response.getOutputStream()); 
				wrRet.write(responseBody); 
				wrRet.flush();
//				wrRet.close();
				
				
				response.flushBuffer();
//				brResponse.close();
//				conn.disconnect();
			} catch (Throwable t) {
				if(DUMP) {
					t.printStackTrace();
				}
				log.error("FORWARD ERROR",t);
				throw new ServletException(t);
			}
		}
	}

}
